package top.ffhome.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class FileUtils {
	/**
	 * 根据文件计算出文件的MD5
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileMD5(File file) {
		if (!file.isFile()) {
			return null;
		}

		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());

		return bigInt.toString(16);
	}

	/**
	 * 根据上传文件名生成保存的文件名,过滤不需要的文件
	 * 
	 * @param fileName
	 * @param types
	 * @return
	 */
	public static String getFileNameByType(String fileName, List<String> types) {
		String type = getFileExt(fileName);
		if (type != null) {
			for (String t : types) {
				if (t.equalsIgnoreCase(type)) {
					return generatePathByDate() + Long.toHexString(IdUtil.createSnowflake(1, 1).nextId()) + "." + t;
				}
			}
			log.warn("没有找到\"{}\"类型的文档!", type);
		}
		return null;
	}

	/**
	 * 去除文件前的路径
	 * @param fileName
	 * @return
	 */
	public static String excludePath(String fileName) {
		String ret = getAfterSeparator(fileName, "/");
		if (ret == null) {
			return getAfterSeparator(fileName, System.getProperty("file.separator"));
		}
		return ret;
	}

	/**
	 * 取得文件的扩展名
	 * @param fileName
	 * @return
	 */
	public static String getFileExt(String fileName) {
		return getAfterSeparator(fileName, ".");
	}

	private static String getAfterSeparator(String str, String separator) {
		if (str == null) {
			return null;
		}
		int i = str.lastIndexOf(separator);
		if (i == -1) {
			return null;
		}
		return str.substring(i + 1);
	}

	private static String generatePathByDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
		return sdf.format(new Date());
	}
}
